package com.lsh.oms.worker.service.task;

import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.JobExecutionSingleShardingContext;
import com.dangdang.ddframe.job.plugin.job.type.dataflow.AbstractIndividualSequenceDataFlowElasticJob;
import com.lsh.base.trace.id.filter.TraceIdSetter;
import com.lsh.oms.core.dao.order.OrderDetailDao;
import com.lsh.oms.core.dao.order.OrderDetailExtDao;
import com.lsh.oms.core.model.order.OrderDetail;
import com.lsh.oms.core.model.order.OrderDetailExt;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author peter
 */
@Component
public class AsyncInsertOrderDetailExtJob extends AbstractIndividualSequenceDataFlowElasticJob<OrderDetail> {

    private final Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private OrderDetailDao orderDetailDao;

    @Autowired
    private OrderDetailExtDao orderDetailExtDao;

    @Override
    public List<OrderDetail> fetchData(JobExecutionSingleShardingContext context) {
        TraceIdSetter.set();
        int fetchSize = context.getFetchDataCount();
        logger.info("异步写入OrderDetailExt查询数据开始。。。fetchSize=" + fetchSize);
        List<OrderDetail> list = orderDetailDao.findListNotInExt(fetchSize);
        logger.info("异步写入OrderDetailExt查询数据结束。。。dataSize=" + list.size());
        return list;
    }

    @Override
    public boolean processData(JobExecutionSingleShardingContext context, OrderDetail detail) {
        if (detail == null) {
            return false;
        }
        Long id = detail.getId();
        String detailExt = detail.getDetailExt();
        logger.info("异步写入OrderDetailExt执行写入开始。。。id=" + id + "，ext=" + detailExt);
        if (id == null || !StringUtils.hasLength(detailExt)) {
            return false;
        }
        OrderDetailExt ext = JSON.parseObject(detailExt, OrderDetailExt.class);
        ext.setVenderId(detail.getVenderId());
        ext.setId(id);
        try {
            int ret = orderDetailExtDao.insert(ext);
            logger.info("异步写入OrderDetailExt执行写入完成。。。id=" + id + "，ret=" + ret);
            return ret > 0;
        } catch (DuplicateKeyException e) {
            logger.error("异步写入OrderDetailExt执行写入重复。。。id=" + id, e);
            return true;
        }
    }
}
